<style scoped>
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }

  .weui-loadmore_line .weui-loadmore__tips {
    background-color: #eee;
  }

  .rj-cell.max span {
    font-size: 16px;
    padding-right: 20px;
  }

  .rj-cell label {
    color: #333;
    font-size: 14px;
    width: 44%;
    display: inline-block;
    padding: 5px 3%;
    text-align: right;
  }

  .rj-cell span {
    font-size: 14px;
    color: #333;
    display: inline-block;
    width: 50%;
  }

  .rj-cell.note label {
    float: left;
  }

  .rj-cell.note span {
    width: 80%;
    display: inline-block;
  }

  .weui-cells {
    margin-top: 0;
  }

  .weui-cells_form {
    background: #fbfbfb;
  }

  .weui-cell {
    background: #fff;
  }

  .weui-cells__title {
    text-align: left;
  }

  .oitem {
    padding: 3px;
  }

  .hide {
    display: none;
  }

  #acts {
    font-size: 0;
  }

  #acts span {
    font-size: 14px;
  }

  .halfbtn {
    display: inline-block;
    width: 49%;
  }

  .weui-label {
    text-align: left;
  }

  .time {
    border: none;
    font-size: 17px;
  }

  .weui-cell_select {
    padding: 10px 15px;
  }

  .weui-select {
    height: auto;
    line-height: normal;
  }


  .weui_uploader_input_wrp {
    float: left;
    position: relative;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 77px;
    height: 77px;
    border: 1px solid #D9D9D9;
  }

  .weui_uploader_hd {
    padding-top: 0;
    padding-right: 0;
    padding-left: 0;
  }

  .weui_uploader_files {
    list-style: none;
  }

  .weui_uploader_input_wrp:before {
    width: 2px;
    height: 39.5px;
  }

  .weui_uploader_input_wrp:before, .weui_uploader_input_wrp:after {
    content: " ";
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    background-color: #D9D9D9;
  }

  .weui_uploader_input {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  }

  .weui_uploader_input_wrp:after {
    width: 39.5px;
    height: 2px;
  }

  .weui_uploader_bd {
    overflow: hidden;
  }

  .weui_cell {
    padding: 10px 15px;
    position: relative;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -webkit-align-items: center;
    -ms-flex-align: center;
    align-items: center;
  }

  .outstore >>> .weui-uploader_files {
    list-style: none;
    overflow-y: hidden;
  }

  .outstore >>> .weui-uploader_file {
    float: left;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 79px;
    background: no-repeat 50%;
    background-size: cover;
  }

  .weui-cell.fir {
    border-top: 0;
  }

  .help {
    text-align: right;
    padding: 5px;
    font-size: 12px;
    color: #bbb;
  }

  .weui_uploader_input_wrp.inrow {
    width: 30px;
    height: 30px;
    margin: 0;
  }

  .weui_uploader_input_wrp:before {
    height: 19.5px;
  }

  .weui_uploader_input_wrp:after {
    width: 19.5px;
  }

  .weui-uploader_file.inrow {
    margin: 0;
    width: 40px;
  }

  li.weui-uploader_file {
    display: inline-block;
    padding: 3px 5px;
  }

  ul#images {
    text-align: right;
  }

  .addPur >>> .ui.selection.dropdown {
    border: none;
  }
  .addPur >>> .ui.dropdown .menu>.item {
    font-size: 18px;
  }
  .addPur >>> .ui.search.dropdown>.text {
    font-size: 18px;
  }

  /*.addPur >>> .ui.search.dropdown>.text {*/
  /*  line-height: 20px;*/
  /*}*/
</style>
<template>
  <div class="addPur" style="overflow: hidden;">
    <div
      style="height: 50px; line-height: 50px; background: #f7f7f7; text-align: center; font-size: 16px; border-bottom: 1px solid #bdbbbc; position: relative">
      录入采购订单
      <a href="javascript:;" @click="$router.back(-1)" style="position: absolute; left: 10px; top: 8px">
        <img src="@/assets/back.png" style="width: 20px"/>
      </a>
    </div>
    <div class="weui-cells weui-cells_form">
      <form action="" method="post" id="formid">
        <div class="cellgroup">
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">采购部门</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" name="deptId" :value="depart.deptId" />
              <input type="hidden" name="department" :value="depart.deptName" />
              <select class="weui-select" v-model="depart">
                <option value="" disabled>请选择</option>
                <option v-for="(item, index) in departments" :key="item.deptId" :value="item">
                  {{item.deptName}}
                </option>
              </select>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd">
              <label class="weui-label">采购主体</label>
            </div>
            <div class="weui-cell__bd">
              <input type="hidden" name="orgid" v-model="org.guid"/>
              <input type="hidden" name="orgname" readonly class="weui-input" :value="org.name"/>
              <select class="weui-select" v-model="org">
                <option value="" disabled>请选择</option>
                <option v-for="(item, index) in orgs" :key="item.guid" :value="item">
                  {{item.name}}
                </option>
              </select>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">入库库房</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" name="srguid" :value="stroom.id" />
              <input type="hidden" name="srname" :value="stroom.name" />
              <select class="weui-select" v-model="stroom">
                <option value="" disabled>请选择</option>
                <option v-for="(item, index) in storerooms" :key="item.id" :value="item">
                  {{item.name}}
                </option>
              </select>
            </div>
          </div>

          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">采购类型</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select" name="type" v-model="types11">
                <option value="" disabled>请选择</option>
                <option v-for="dict in types1" :value="dict.dictValue" :key="dict.dictValue">{{dict.dictLabel}}</option>
              </select>
            </div>
          </div>

          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">供应商</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" name="supplierid" :value="partb.id" />
              <input type="hidden" name="supplier" :value="partb.name" />
              <model-list-select :list="suppliers"
                                 v-model="partbid"
                                 option-value="id"
                                 option-text="name"
                                 placeholder="请选择">
              </model-list-select>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd">
              <label class="weui-label">采购日期</label>
            </div>
            <div class="weui-cell__bd">
              <input type="text" id='datetime-picker' class="time" placeholder="请选择采购日期" autocomplete="off"/>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">备注</label></div>
            <div class="weui-cell__bd">
              <textarea class="weui-textarea" name="remark" placeholder="请输备注内容" rows="2"></textarea>
            </div>
          </div>
        </div>
        <div class="weui-cell fir">
          <div class="weui-cell__hd"><label class="weui-label">附件上传</label></div>
          <div class="weui-cell__ft">
            <div class="weui_uploader_bd">
              <ul class="weui_uploader_files"></ul>
              <div class="weui_uploader_input_wrp inrow">
                <UploadFile3 class="weui_uploader_input" v-on:pushfile="setFile"></UploadFile3>
              </div>
            </div>
          </div>
          <ul class="weui-uploader_files" id="images">
            <li class="weui-uploader_file" v-for="(fil, index) in filenames" @click=delFile(fil,fileids[index])>
              {{fil}}
            </li>
          </ul>
        </div>
        <PurchaseItem v-for="(item, index) in oitems" :key="index" :itemNo="item" :isLast="index+1 == oitems.length" :productCate="productCate" :types="productTypes" @doAddItem="addItem(index + 1)"
                      @doDelItem="delItem" @changeData="takeItem"></PurchaseItem>
        <div class="weui-btn-area">
          <a class="weui-btn weui-btn_primary subbtn" href="javascript:" @click="postForm()">提交</a>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
  import 'vue-search-select/dist/VueSearchSelect.css'
  import { ModelListSelect } from 'vue-search-select'
  import PurchaseItem from "./PurchaseItem";
  import UploadFile3 from "../common/UploadFile3";
  import qs from 'qs';

  export default {
    name: 'AddPurchase2',
    data() {
      return {
        organizations: [],
        storerooms: [],
        stroom: '',
        org: '',
        purdate: '',
        departments: [],
        depart: '',
        suppliers: [],
        partb: '',
        partbid: '',
        oitems: [0],
        filenames: [],
        fileids: [],
        suppliertype: '',
        productCate: '',
        types: '',
        productTypes: [],
        model: {
          items: []
        },
        orgs: [],
        types1:[],
        types11:'',
      }
    },
    components: {ModelListSelect, PurchaseItem, UploadFile3},
    async mounted() {
      let that = this;
      //日历初始化
      $("#datetime-picker").calendar();
      $("#datetime-picker").change(function () {
        that.purdate = $(this).val().replace(/\//g, '-');
      })

      this.getDepartment();
      this.getOrgs();
      this.getTypes1();
      this.getsuppliers();
      this.getProducttypes();
    },
    watch: {
      org: function (val) {
        this.getSr(val.guid);
      },
      partbid: function (val) {
        this.partb = this.suppliers.filter(item =>{
          return item.id == val;
        })[0] || '';
      }
    },
    methods: {
      takeItem: function(val) {
        // if (!val) return;
        if (this.model.items.some(item => {
          return item.index == val.index;
        })) {
          this.model.items = this.model.items.map(item => {
            if (item.index == val.index) {
              return val;
            }
            return item;
          })
        } else {
          this.model.items.push(val);
        }
      },
      addItem: function (index) {
        this.oitems.push(index);
      },
      delItem: function () {
        this.oitems.pop();
        this.model.items.pop()
      },
      delFile: function (name, id) {
        let that = this;
        $.confirm('确定要删除？', function () {
          that.axios({
            method: 'post',
            url: '/prod-api/common/delete',
            params: {id: id}
          })
          that.fileids = that.fileids.filter(item => {
            return item != id;
          })
          that.filenames = that.filenames.filter(item => {
            return item != name;
          })
        })
      },
      setFile: function (file) {
        this.filenames.push(file.name);
        this.fileids.push(file.id);
      },
      getProducttypes: async function() {
        let that = this;
        await this.axios({
          method: 'get',
          url: '/prod-api/system/dict/data/type/product_type',
        }).then(response => {
          if (response.data.code == 200) {
            that.productTypes = response.data.data.filter(item => [2, 4].includes(parseInt(item.dictValue)));
          } else {
            this.toastText('获取货品类型数据失败');
          }
        });
      },
      getSr: function(orgId) {
        this.axios({
          method: 'get',
          url: '/prod-api/getStoreRoomByOrgIdOrPermissions',
          params: {guid: orgId, enable: 1}
        }).then(response => {
          if (response.data.code == 200) {
            this.storerooms = response.data.data;
          } else {
            this.toastText('获取库房数据失败');
          }
        });
      },
      getsuppliers: function() {
        this.axios({
          method: 'get',
          url: '/prod-api/getSuppliers',
          // params: {types: this.suppliertype}
        }).then(response => {
          if (response.data.code == 200) {
            this.suppliers = response.data.data;
          } else {
            this.toastText('获取供应商数据失败')
          }
        });
      },
      getOrgs: function() {
        this.axios({
          method: 'get',
          url: '/prod-api/getOrgs',
        }).then(response => {
          if (response.data.code == 200) {
            this.orgs = response.data.data;
          } else {
            this.toastText('获取主体数据失败')
          }
        });
      },

      getTypes1:async function (){
        await this.axios({
          method:'get',
          url:'/prod-api/system/dict/data/type/purchasebill_type',
        }).then(response=>{
          if(response.data.code == 200){
            this.types1=response.data.data;
          }else {
            this.toastText('获取采购类型失败')
          }
        });
      },

      getDepartment: function () {
        let that = this;
        this.axios({
          method: 'get',
          url: '/prod-api/getDepsByPermissionCode',
          params: {code: 48}
        }).then(response => {
          if (response.data.code == 200) {
            that.departments = response.data.data;
            this.depart = response.data.result[0] || '';
          }  else {
            this.toastText('获取部门数据失败');
          }
        });
      },
      //提交表单数据
      postForm: function () {
        let that = this;
        //表单校验
        if (!this.checkFormElm()) {
          return false;
        }
        //防止重复提交
        $('.subbtn').attr("disabled",true).css("pointer-events","none");
        //显示提交状态
        $.showLoading("正在提交");
        let postData = this.serialize2Obj($("#formid").serializeArray());
        postData.items = this.model.items;
        postData['purchdate'] = this.purdate;
        postData.fileIds = this.fileids.join(',');
        // postData = JSON.parse(postData)
        this.axios({
          method: 'post',
          url: `/prod-api/purchasebill/purchasebill/save?fileIds=${postData.fileIds}`,
          data: postData
        }).then(response => {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();

          if (response.data.code == 200) {
            this.toastSuccess("保存成功");
            this.$router.push({name: 'PurchaseList2'});
          } else if (response.data.msg) {
            this.toastText(response.data.msg);
          } else {
            this.toastError('系统错误');
          }
        }).catch(function (error) {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();
          that.toastError('系统错误');
        });
      },
      checkFormElm: function () {
        if (!this.checkNull(this.types11)){
          this.toastText('请选择采购类型');
          return false;
        }
        if (!this.checkNull(this.depart)) {
          this.toastText('请选择采购部门');
          return false;
        }
        if (!this.checkNull(this.stroom)) {
          this.toastText('请选择入库库房');
          return false;
        }
        if (!this.checkNull(this.partb)) {
          this.toastText('请选择供应商');
          return false;
        }
        if (!this.checkNull(this.purdate)) {
          this.toastText('请选择采购日期');
          return false;
        }
        if (!this.checkEmy('product')) {
          this.toastText('产品有误');
          return false;
        }
        if (this.model.items.some(item => !item.spname)) {
          this.toastText('规格有误');
          return false;
        }
        if (!this.checkEmy('count')) {
          this.toastText('数量有误');
          return false;
        }
        if (!this.checkEmy2('price')) {
          this.toastText('单价有误');
          return false;
        }
        return true;
      },
      checkEmy: function(elem){
        let isFieldNotEmy = true;
        for (let i=0; i<$('.' + elem + ':not(:hidden)').length; i++) {
          if ($('.' + elem + ':not(:hidden)').eq(i).val() == 0 || $('.' + elem + ':not(:hidden)').eq(i).val() == '') {
            isFieldNotEmy = false;
            break;
          }
        }
        return isFieldNotEmy;
      }
    }
  }
</script>
